/**
 *
 */
package com.lanyou.esb.servicemix.monitor.rest;

import java.net.CookieHandler;
import java.util.Date;

import com.lanyou.esb.servicemix.monitor.ESBServer;
import com.lanyou.esb.servicemix.monitor.rest.adapter.CustomDateTypeAdapter;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.converter.GsonConverter;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import sun.misc.BASE64Decoder;

/**
 * @author gonglei
 */
public class RestFactory {

    private ESBServer esbServer;

    private UserCookieManager cookieManager;

    private MonitorService monitorService;

    private ProxyService proxyService;

    public RestFactory(ESBServer esbServer) {
        this.esbServer = esbServer;
        String endpoint = "http://" + esbServer.getServerAddres() + ":" + esbServer.getPort() + "/system/console/";

        Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new CustomDateTypeAdapter()).create();
        CookieHandler.setDefault(new UserCookieManager());
        GsonConverter gsonConverter = new GsonConverter(gson);
        String authBase64=getBASE64(esbServer.getUserName()+":"+esbServer.getPassword());
        RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(endpoint)
                .setConverter(gsonConverter).setRequestInterceptor(new RequestInterceptor() {
                    @Override
                    public void intercept(RequestFacade request) {
                        request.addHeader("Authorization", "Basic " + authBase64);
                        if (cookieManager != null) {
                            request.addHeader("Set-Cookie", "sessionId=" + cookieManager.getSessionId());
                        }
                    }
                }).build();
        monitorService = restAdapter.create(MonitorService.class);

        //创建代理转发bundle的监控接口
        String proxyEndpoint = "http://" + esbServer.getServerAddres() + ":" + esbServer.getPort() + "/cxf/proxy/services/";
        RestAdapter proxyRestAdapter = new RestAdapter.Builder().setEndpoint(proxyEndpoint)
                .setConverter(gsonConverter).build();
        proxyService = proxyRestAdapter.create(ProxyService.class);
    }

    public MonitorService getMonitorService() {
        return monitorService;
    }

    public ProxyService getProxyService() {
        return proxyService;
    }

    private String getFromBASE64(String s) {
        if (s == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b);
        } catch (Exception e) {
            return null;
        }
    }

    public static String getBASE64(String s) {
        if (s == null)
            return null;
        return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
    }

}
